package web.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.RandomStringUtils;

import web.servlet.dto.DtoFactory;
import data.model.User;

public class ResetServlet extends AbstractJsonCapableServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        final User user = dataLayer.findUserByEmail(request.getParameter("email"));

        final String password = generateRandomPassword();
        user.setPassword(password);
        dataLayer.updateObject(user);

        sendPasswordEmail(user.getEmail(), password);

        jsonHandler.writeAsJson(DtoFactory.createMessage("An email containing your new password has been sent to your email address"), response);
    }

    private String generateRandomPassword() {
        return RandomStringUtils.randomAlphanumeric(8);
    }

    private void sendPasswordEmail(String email, String password) {
        final Map<String, String> mailTemplateParams = new HashMap<String, String>();
        mailTemplateParams.put("password.plainTextPassword", password);
        mailTemplateParams.put("password.loginUrl", HOST + "/index.jsp");

        emailLayer.sendEmail(email, "password.subject", "password.body", mailTemplateParams);
    }
}
